package com.ktgj.customer.controller;

import java.io.DataInput;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.List;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ktgj.common.core.constant.CustomerConstants;
import com.ktgj.common.log.annotation.SignatureValidation;
import com.ktgj.customer.domain.Customer;
import com.ktgj.customer.domain.DepositBusiness;
import com.ktgj.customer.domain.Employee;
import com.ktgj.customer.domain.MallProduct;
import com.ktgj.customer.domain.vo.DepositInfo;
import com.ktgj.customer.domain.vo.GoldListVo;
import com.ktgj.customer.service.IDepositBusinessService;
import com.ktgj.customer.service.ILoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ktgj.common.log.annotation.Log;
import com.ktgj.common.log.enums.BusinessType;
import com.ktgj.common.security.annotation.PreAuthorize;
import com.ktgj.common.core.web.controller.BaseController;
import com.ktgj.common.core.web.domain.AjaxResult;
import com.ktgj.common.core.utils.poi.ExcelUtil;
import com.ktgj.common.core.web.page.TableDataInfo;

/**
 * 预留款业务Controller
 * 
 * @author ruoyi
 * @date 2021-07-27
 */
@ControllerAdvice
@RestController
@RequestMapping("/business")
public class DepositBusinessController extends BaseController
{
    @Autowired
    private IDepositBusinessService depositBusinessService;

    @Autowired
    private ILoginService loginService;

    /**
     * 查询预留款业务列表
     */
    //@PreAuthorize(hasPermi = "system:business:list")
    @GetMapping("/list")
    public TableDataInfo list(DepositBusiness depositBusiness)
    {
        startPage();
        List<DepositBusiness> list = depositBusinessService.selectDepositBusinessList(depositBusiness);
        return getDataTable(list);
    }

    /**
     * 导出预留款业务列表
     */
    //@PreAuthorize(hasPermi = "system:business:export")
    @Log(title = "预留款业务", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DepositBusiness depositBusiness) throws IOException
    {
        List<DepositBusiness> list = depositBusinessService.selectDepositBusinessList(depositBusiness);
        ExcelUtil<DepositBusiness> util = new ExcelUtil<DepositBusiness>(DepositBusiness.class);
        util.exportExcel(response, list, "预留款业务数据");
    }

    /**
     * 获取预留款业务详细信息
     */
    //@PreAuthorize(hasPermi = "system:business:query")goldCoinAudit
    @GetMapping(value = "/{businessId}")
    public AjaxResult getInfo(@PathVariable("businessId") Long businessId)
    {
        return AjaxResult.success(depositBusinessService.selectDepositBusinessById(businessId));
    }

    /**
     * 新增预留款业务
     */
    //@PreAuthorize(hasPermi = "system:business:add")
    @Log(title = "预留款业务", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DepositBusiness depositBusiness)
    {
        Long aLong = depositBusinessService.insertDepositBusiness(depositBusiness);
        if (aLong > 0){
            return AjaxResult.success("新增成功");
        }
        else {
            return AjaxResult.error("新增失败");
        }
    }

    /**
     * 新增预留款业务
     */
    @PostMapping("/addReserveMoney")
    public Long addReserveMoney(@RequestBody DepositBusiness depositBusiness)
    {
        Long aLong = depositBusinessService.insertDepositBusiness(depositBusiness);
        return aLong;
    }

    /**
     * 退款（添加会员预留款记录）
     */
    @PostMapping("/refund")
    public int refund(@RequestBody DepositBusiness depositBusiness)
    {
        Long aLong = depositBusinessService.insertDepositBusiness(depositBusiness);
        if (aLong > 0){
            return 1;
        }
        else {
            return 0;
        }
    }

    /**
     * 修改预留款业务
     */
    //@PreAuthorize(hasPermi = "system:business:edit")
    @Log(title = "预留款业务", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DepositBusiness depositBusiness)
    {
        return toAjax(depositBusinessService.updateDepositBusiness(depositBusiness));
    }

    /**
     * 删除预留款业务
     */
    //@PreAuthorize(hasPermi = "system:business:remove")
    @Log(title = "预留款业务", businessType = BusinessType.DELETE)
	@DeleteMapping("/{businessIds}")
    public AjaxResult remove(@PathVariable Long[] businessIds)
    {
        return toAjax(depositBusinessService.deleteDepositBusinessByIds(businessIds));
    }

    /**
     * 查看用户可用预留款
     * @param request
     * @return
     */
    //@SignatureValidation
    @PostMapping("/queyUserDepositBusiness")
    public AjaxResult queyUserDepositBusiness(HttpServletRequest request) {
        Customer customer;
        try {
            customer = loginService.getLoginCustomer(request);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success(depositBusinessService.queyUserDepositBusiness(customer.getCustomerId()));
    }

    /**
     * 查看用户可用预留款(远程)
     */
    @PostMapping("/depositBusiness")
    public AjaxResult depositBusiness(HttpServletRequest request) {
        Customer customer;
        try {
            customer = loginService.getLoginCustomer(request);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success(depositBusinessService.queyUserDepositBusiness(customer.getCustomerId()));
    }

    /**
     * 查看用户可用预留款
     * @param token
     * @return
     */
    @PostMapping("/selectAvailableGold")
    public AjaxResult selectAvailableGold(@RequestParam("token")String token) {
        Customer customer;
        try {
            customer = loginService.getLoginCustomerByToken(token);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success(depositBusinessService.queyUserDepositBusiness(customer.getCustomerId()));
    }

    /**
     * 查看用户可用预留款（CRM）
     * @param customerId
     * @return
     */
    @PostMapping("/selectAvailableGoldByCustomerId")
    public AjaxResult selectAvailableGoldByCustomerId(@RequestParam("customerId") Long customerId) {
        return AjaxResult.success(depositBusinessService.queyUserDepositBusiness(customerId));
    }

    /**
     * 我的资产
     * */
    //@SignatureValidation
    @PostMapping("/selectDepositBusinessByCustomerId")
    public AjaxResult selectDepositBusinessByCustomerId(HttpServletRequest request, @RequestBody Map<String, Object> map) {
        String operationtime = map.get("operationtime").toString();
        Customer customer;
        try {
            customer = loginService.getLoginCustomer(request);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success(depositBusinessService.selectDepositBusinessByCustomerId(customer.getCustomerId(), operationtime));
    }

    /**
     * 预留款审核
     * */
    @PostMapping("/goldCoinAudit")
    public AjaxResult goldCoinAudit(HttpServletRequest request, @RequestBody Map<String, Object> map){
        Long id = Long.valueOf(map.get("id").toString());
        String remark;
        if (map.get("remark") != null && !map.get("remark").equals("")){
            remark = map.get("remark").toString();
        }
        else {
            return AjaxResult.error("审核备注必填");
        }

        Employee loginEmployee = loginService.getLoginEmployee(request);
        if (loginEmployee == null){
            return AjaxResult.error("登陆已过期");
        }

        boolean b;
        try {
            b = depositBusinessService.depositAudit(id, remark);
        } catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }

        if (b){
            return AjaxResult.success("审核成功");
        }
        else {
            return AjaxResult.error("审核失败");
        }
    }

    /**
     * 预留款审核（系统管理员）
     * */
    @PostMapping("/manageAudit")
    public boolean manageAudit(@RequestBody Map<String, Object> map){
        Long id = Long.valueOf(map.get("id").toString());
        String remark;
        if (map.get("remark") != null && !map.get("remark").equals("")){
            remark = map.get("remark").toString();
        }
        else {
            return false;
        }

        boolean b;
        try {
            b = depositBusinessService.goldCoinAudit(10l, id, remark);
        } catch (Exception e){
            return false;
        }

        if (b){
            return true;
        }
        else {
            return false;
        }
    }

    /**
     * 消费预留款
     * @param depositInfo
     * @return
     */
    @PostMapping("/spendDeposit")
    public AjaxResult spendDeposit(@RequestBody DepositInfo depositInfo)
    {
        boolean result;
        result = depositBusinessService.spendDeposit(depositInfo);
        if (result)
        {
            return AjaxResult.success("花费预留款成功！");
        }
        return AjaxResult.error("花费预留款失败！");
    }

    /**
     * 预留款列表
     * */
    @PostMapping("/goldList")
    public TableDataInfo goldList(@RequestBody GoldListVo goldListVo){
        startPage();
        List<DepositBusiness> depositBusinessList = depositBusinessService.goldList(goldListVo);
        return getDataTable(depositBusinessList);
    }

    /**
     * 预留款调整
     * */
    @PostMapping("/goldAdjustment")
    public AjaxResult goldAdjustment(HttpServletRequest request, @RequestBody DepositBusiness depositBusiness){
        int i;
        try {
            i = depositBusinessService.goldAdjustment(request, depositBusiness);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

        if (i > 0){
            return AjaxResult.success("调整成功");
        }
        else {
            return AjaxResult.success("调整失败");
        }
    }

    /**
     * 当前会员可支配的预留款
     * */
    @PostMapping("/dominateGold")
    public BigDecimal dominateGold(@RequestBody Map<String, Object> map){
        Long id = Long.valueOf(map.get("id").toString());
        BigDecimal amount = depositBusinessService.dominateGold(id);
        return amount;
    }

    /**
     * 当前会员可支配的预留款
     * */
    @PostMapping("/BackDominateGold")
    public BigDecimal BackDominateGold(HttpServletRequest request){
        BigDecimal amount;
        Customer customer;
        try {
            customer = loginService.getLoginCustomer(request);
        } catch (Exception e){
            return new BigDecimal(0);
        }
        if (customer != null){
            amount = depositBusinessService.dominateGold(customer.getCustomerId());
        }
        else {
            amount = new BigDecimal(0);
        }
        return amount;
    }

    /**
     * 订单号查预留款记录
     * */
    @PostMapping("/audit")
    public boolean audit(@RequestParam("orderNum") String orderNum){
        boolean flag = depositBusinessService.audit(orderNum);
        return flag;
    }
}
